<template>
  <view class="comments-container">
    <!-- 头部区域 -->
    <view class="header">
      <text class="title">我的评论</text>
    </view>

    <!-- 评论列表 -->
    <view class="comments-list">
      <view class="comment-item" v-for="(comment, index) in comments" :key="index">
        <view class="comment-header">
          <view class="user-info">
            <text class="username">{{ comment.username || '我' }}</text>
            <text class="comment-time">{{ formatDateTime(comment.createTime) }}</text>
          </view>
          <view class="post-info">
            <text class="post-title">{{ comment.postTitle || '原帖' }}</text>
          </view>
        </view>

        <view class="comment-content">
          <view class="comment-text-container">
            <text class="reply-info" v-if="comment.replyToUsername">
              回复 <text class="reply-name">@{{ comment.replyToUsername }}</text
              >：
            </text>
            <text class="comment-text">{{ comment.content }}</text>
          </view>
        </view>

        <view class="comment-footer">
          <view class="post-preview" @tap="goToPost(comment.postId)">
            <text class="preview-text">查看帖子</text>
            <text class="preview-arrow">></text>
          </view>
          <view class="action-buttons">
            <view class="action-button delete" @tap="deleteComment(comment.id)">
              <text class="action-text">删除</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态提示 -->
    <view class="empty-list" v-if="comments.length === 0 && !isLoading">
      <image class="empty-icon" src="/static/images/empty.png" mode="aspectFit" />
      <text class="empty-text">暂无评论记录</text>
    </view>

    <!-- 加载中提示 -->
    <view class="loading" v-if="isLoading">
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script>
import { queryComment, deleteComment } from '@/api/post'

export default {
  data() {
    return {
      comments: [],
      isLoading: false,
      isLoggedIn: false,
    }
  },

  methods: {
    // 获取用户评论
    async fetchUserComments() {
      if (!this.isLoggedIn) {
        uni.showToast({
          title: '请先登录',
          icon: 'none',
        })
        return
      }

      this.isLoading = true

      try {
        const res = await queryComment()
        if (res.statusCode === 200 && res.data) {
          const responseData = res.data
          if (responseData.code === 200) {
            this.comments = responseData.data || []

            // 对评论按时间倒序排序，最新的在前面
            this.comments.sort((a, b) => {
              return new Date(b.createTime) - new Date(a.createTime)
            })
          } else {
            uni.showToast({
              title: responseData.info || '获取评论失败',
              icon: 'none',
            })
          }
        }
      } catch (error) {
        console.error('获取评论失败', error)
        uni.showToast({
          title: '获取评论失败，请稍后再试',
          icon: 'none',
        })
      } finally {
        this.isLoading = false
      }
    },

    // 检查登录状态
    checkLoginStatus() {
      const token = uni.getStorageSync('token')
      const userInfo = uni.getStorageSync('userInfo')
      this.isLoggedIn = !!(token && userInfo)

      if (!this.isLoggedIn) {
        uni.showModal({
          title: '提示',
          content: '请先登录',
          showCancel: false,
          success: () => {
            uni.navigateTo({
              url: '/pages/login/login',
            })
          },
        })
      } else {
        this.fetchUserComments()
      }
    },

    // 跳转到帖子详情
    goToPost(postId) {
      if (!postId) return

      uni.navigateTo({
        url: `/pages/posts/detail?id=${postId}`,
      })
    },

    // 删除评论
    deleteComment(commentId) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这条评论吗？',
        success: async (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: '删除中...',
            })

            try {
              const res = await deleteComment(commentId)

              if (res.statusCode === 200 && res.data) {
                const responseData = res.data

                if (responseData.code === 200) {
                  // 从列表中移除
                  this.comments = this.comments.filter((item) => item.id !== commentId)

                  uni.showToast({
                    title: '删除成功',
                    icon: 'success',
                  })
                } else {
                  uni.showToast({
                    title: responseData.info || '删除失败',
                    icon: 'none',
                  })
                }
              } else {
                uni.showToast({
                  title: '删除失败',
                  icon: 'none',
                })
              }
            } catch (error) {
              console.error('删除评论失败:', error)
              uni.showToast({
                title: '删除失败，请稍后再试',
                icon: 'none',
              })
            } finally {
              uni.hideLoading()
            }
          }
        },
      })
    },

    // 格式化日期时间
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return '-'

      try {
        const date = new Date(dateTimeStr)
        const now = new Date()
        const diffMs = now - date
        const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))

        if (diffDays === 0) {
          // 今天
          const hours = date.getHours().toString().padStart(2, '0')
          const minutes = date.getMinutes().toString().padStart(2, '0')
          return `今天 ${hours}:${minutes}`
        } else if (diffDays === 1) {
          // 昨天
          const hours = date.getHours().toString().padStart(2, '0')
          const minutes = date.getMinutes().toString().padStart(2, '0')
          return `昨天 ${hours}:${minutes}`
        } else if (diffDays < 7) {
          // 一周内
          return `${diffDays}天前`
        } else {
          // 超过一周
          const year = date.getFullYear()
          const month = (date.getMonth() + 1).toString().padStart(2, '0')
          const day = date.getDate().toString().padStart(2, '0')
          return `${year}-${month}-${day}`
        }
      } catch (error) {
        return dateTimeStr
      }
    },
  },

  onLoad() {
    this.checkLoginStatus()
  },

  onShow() {
    if (this.isLoggedIn) {
      this.fetchUserComments()
    } else {
      this.checkLoginStatus()
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.fetchUserComments().then(() => {
      uni.stopPullDownRefresh()
    })
  },
}
</script>

<style lang="scss">
// 薰衣草紫主题色
$theme-color: #9370db;
$light-theme-color: #e6e6fa;
$text-color: #333333;
$border-color: #eeeeee;
$danger-color: #ff6b6b;

.comments-container {
  min-height: 100vh;
  background-color: #f8f8f8;

  .header {
    background: linear-gradient(180deg, $theme-color 0%, $light-theme-color 100%);
    padding: 40rpx 30rpx;

    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #ffffff;
    }
  }

  .comments-list {
    padding: 20rpx;

    .comment-item {
      background-color: #ffffff;
      border-radius: 12rpx;
      padding: 24rpx;
      margin-bottom: 20rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

      .comment-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;

        .user-info {
          display: flex;
          align-items: center;

          .username {
            font-size: 28rpx;
            font-weight: bold;
            color: $theme-color;
            margin-right: 12rpx;
          }

          .comment-time {
            font-size: 24rpx;
            color: #999999;
          }
        }

        .post-info {
          .post-title {
            font-size: 26rpx;
            color: #666666;
            border: 1px solid #eeeeee;
            padding: 2rpx 10rpx;
            border-radius: 12rpx;
          }
        }
      }

      .comment-content {
        margin-bottom: 16rpx;

        .comment-text-container {
          background-color: #f9f9f9;
          padding: 16rpx;
          border-radius: 8rpx;

          .reply-info {
            font-size: 26rpx;
            color: #666666;

            .reply-name {
              color: $theme-color;
            }
          }

          .comment-text {
            font-size: 28rpx;
            color: $text-color;
            line-height: 1.5;
            word-break: break-all;
          }
        }
      }

      .comment-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .post-preview {
          display: flex;
          align-items: center;
          background-color: #f0f0f0;
          padding: 8rpx 16rpx;
          border-radius: 20rpx;

          .preview-text {
            font-size: 24rpx;
            color: #666666;
          }

          .preview-arrow {
            margin-left: 6rpx;
            font-size: 24rpx;
            color: #999999;
          }
        }

        .action-buttons {
          display: flex;

          .action-button {
            margin-left: 20rpx;
            background-color: #f5f5f5;
            padding: 8rpx 16rpx;
            border-radius: 20rpx;

            &.delete {
              background-color: #fff0f0;

              .action-text {
                color: $danger-color;
              }
            }

            .action-text {
              font-size: 24rpx;
              color: #666666;
            }
          }
        }
      }
    }
  }

  .empty-list {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 100rpx 0;

    .empty-icon {
      width: 160rpx;
      height: 160rpx;
      margin-bottom: 20rpx;
      opacity: 0.5;
    }

    .empty-text {
      font-size: 28rpx;
      color: #999999;
    }
  }

  .loading {
    display: flex;
    justify-content: center;
    padding: 30rpx 0;

    .loading-text {
      font-size: 28rpx;
      color: #999999;
    }
  }
}
</style>
